﻿using Colorful.Furniture.Enum;
using Colorful.Furniture.ErpOrderManagement;
using Colorful.Furniture.Extensions;
using Microsoft.Extensions.Logging;
using System;
using System.Data;
using System.Drawing;
using Volo.Abp.BackgroundJobs;
using Volo.Abp.DependencyInjection;
using Colorful.Furniture.ErpCustomerManagement;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using FreeSql;
using Colorful.Furniture.FinanceSdk;
using Dop.Core;
using System.Threading.Tasks;
using Volo.Abp;
using Colorful.Furniture.BasicDataManagement;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Colorful.Furniture.ResultManagement;
using Flurl.Http;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Colorful.Furniture.BackgroundManagement;

/// <summary>
/// 推送订单充值失败信息-后台作业
/// </summary>
public class SentNotifyFailJob : BackgroundJob<SentNotifyFailArgs>, ISingletonDependency
{
    private readonly IFreeSql _freeSql;
    private readonly ILogger<SentNotifyFailArgs> _logger;
    private readonly IBaseRepository<RechargeOrderCallbackLog> _customerOrderCallbackLogRepository;
    private readonly IBackgroundJobManager _backgroundJobManager;
    private readonly FileConfig _fileConfig;

    public SentNotifyFailJob(
        IBackgroundJobManager backgroundJobManager,
        IFreeSql freeSql,
        ILogger<SentNotifyFailArgs> logger,
        IBaseRepository<RechargeOrderCallbackLog> customerOrderCallbackLogRepository,
        IOptions<FileConfig> fileConfig
    )
    {
        _backgroundJobManager = backgroundJobManager;
        _freeSql = freeSql;
        _logger = logger;
        _customerOrderCallbackLogRepository = customerOrderCallbackLogRepository;
        _fileConfig = fileConfig.Value;
    }


    /// <summary>
    /// 执行推送客户提交的回调地址
    /// </summary>
    /// <param name="args"></param>
    public override async void Execute(SentNotifyFailArgs args)
    {
        // 暂停0.8秒
        await Task.Delay(800); // 1000毫秒等于1秒

        _logger.LogWarning($"开始向客户地址推送回调-充值账号：{args.RechargeAccount}");

        if (args.Status == EnumOrderStatus.充值失败 || args.Status == EnumOrderStatus.充值成功)
        {
            //检查商户信息
            var customerInfo = await _freeSql.Select<Customer>()
                .Where(x => x.Code == args.Code)
                .FirstAsync();

            var status = args.Status == EnumOrderStatus.充值成功 ? "01" :
                args.Status == EnumOrderStatus.充值中 ? "02" : "03";
            var urlStr =
                $"merchantId={args.Code}&outTradeNo={args.OutTradeNo}&rechargeAccount={args.RechargeAccount}&status={status}";
            var signTemp = urlStr + "&key=" + customerInfo.Key;
            var sign = Md5Encrypt.Md5Encrypt32(signTemp);
            var remark = args.Remark;
            var message = args.Status == EnumOrderStatus.充值中 ? "充值处理中" : remark;
            var postData = urlStr + $"&message={message}&sign={sign}";

            if (!string.IsNullOrEmpty(args.NotifyUrl))
            {
                _logger.LogWarning($"进入-下单客户地址推送回调-充值账号：{args.RechargeAccount}");

                //提交
                using (HttpClient client = new HttpClient())
                {
                    using (HttpContent httpContent = new StringContent(postData, Encoding.UTF8))
                    {
                        try
                        {
                            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                            HttpResponseMessage response = client.PostAsync(args.NotifyUrl, httpContent).Result;
                            var result = response.Content.ReadAsStringAsync().Result.CutSubstring(200);
                            _logger.LogWarning($"向客户回调推送成功-充值账号：{args.RechargeAccount}，客户端返回内容：{result}");
                        }
                        catch (Exception e)
                        {
                            _logger.LogWarning($"向客户回调推送失败-充值账号：{args.RechargeAccount}，客户端返回内容：{e.Message}");
                        }
                    }
                }
            }

        }

    }


}


/// <summary>
/// 推送订单充值失败信息请求体
/// </summary>
public class SentNotifyFailArgs
{
    /// <summary>
    /// 回调地址
    /// </summary>
    public string NotifyUrl { get; set; }

    /// <summary>
    ///  备注
    /// </summary>
    public string Remark { get; set; }

    /// <summary>
    /// 订单状态：3：订单失败、2：充值中、1：订单完成
    /// </summary>
    public EnumOrderStatus? Status { get; set; }

    /// <summary>
    /// 客户编号
    /// </summary>
    public int? Code { get; set; }

    /// <summary>
    /// 合作商唯一订单号
    /// </summary>
    public string OutTradeNo { get; set; }

    /// <summary>
    /// 充值账号
    /// </summary>
    public string RechargeAccount { get; set; }

}
